/**
 * This file is part of jCGT (the Java Cooperative Game Theory library).
 *
 * jCGT is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * jCGT is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public License
 * along with jCGT.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package cooperativegametheory.gui;

import cooperativegametheory.solutionfunctions.SolutionFunction;
import javax.swing.JComboBox;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Jonas Brekle <jonas.brekle@gmail.com>
 */
public class CGT_GUI extends javax.swing.JFrame {

    /** Creates new form CGTFrame */
    public CGT_GUI() {
        initComponents();
//        try {
//            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//        } catch (ClassNotFoundException ex) {
//            Logger.getLogger(CGTFrame.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            Logger.getLogger(CGTFrame.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            Logger.getLogger(CGTFrame.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (UnsupportedLookAndFeelException ex) {
//            Logger.getLogger(CGTFrame.class.getName()).log(Level.SEVERE, null, ex);
//        }
        
          cfSettingsContainer.setLayout(new java.awt.BorderLayout());
    }
    

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        sfSelGroup = new javax.swing.ButtonGroup();
        cfSelGroup = new javax.swing.ButtonGroup();
        statusField = new javax.swing.JTextField();
        progressBar = new javax.swing.JProgressBar();
        jPanel2 = new javax.swing.JPanel();
        cfSettingsContainer = new javax.swing.JPanel();
        gameSelector = new javax.swing.JComboBox();
        metaCheckbox = new javax.swing.JCheckBox();
        metaGameSelector = new javax.swing.JComboBox();
        jPanel3 = new javax.swing.JPanel();
        calculateButton = new javax.swing.JButton();
        sfSettingsContainer = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        solutionValueTable = new javax.swing.JTable();
        solutionSelector = new javax.swing.JComboBox();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Cooperative Game Theory");

        statusField.setText("Status ...");
        statusField.setEnabled(false);
        statusField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                statusFieldActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Game"));

        cfSettingsContainer.setBorder(javax.swing.BorderFactory.createTitledBorder("Game Settings"));

        javax.swing.GroupLayout cfSettingsContainerLayout = new javax.swing.GroupLayout(cfSettingsContainer);
        cfSettingsContainer.setLayout(cfSettingsContainerLayout);
        cfSettingsContainerLayout.setHorizontalGroup(
            cfSettingsContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 398, Short.MAX_VALUE)
        );
        cfSettingsContainerLayout.setVerticalGroup(
            cfSettingsContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 227, Short.MAX_VALUE)
        );

        gameSelector.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Gloves Game", "Voting Game", "Apex Game", "Unanimity Game", "Maschler Game", " " }));
        gameSelector.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                gameSelectorActionPerformed(evt);
            }
        });

        metaCheckbox.setText("meta game");
        metaCheckbox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                metaCheckboxActionPerformed(evt);
            }
        });

        metaGameSelector.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Harsanyi Dividend", "Myerson Game", "Permission Game", "Use Game", " " }));

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, metaCheckbox, org.jdesktop.beansbinding.ELProperty.create("${selected}"), metaGameSelector, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        metaGameSelector.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                metaGameSelectorActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(gameSelector, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(metaCheckbox))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(metaGameSelector, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cfSettingsContainer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(gameSelector, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(metaCheckbox)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(metaGameSelector, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(164, Short.MAX_VALUE))
            .addComponent(cfSettingsContainer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Solution"));

        calculateButton.setText("Calculate");
        calculateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                calculateButtonActionPerformed(evt);
            }
        });

        sfSettingsContainer.setBorder(javax.swing.BorderFactory.createTitledBorder("Solution Settings"));

        javax.swing.GroupLayout sfSettingsContainerLayout = new javax.swing.GroupLayout(sfSettingsContainer);
        sfSettingsContainer.setLayout(sfSettingsContainerLayout);
        sfSettingsContainerLayout.setHorizontalGroup(
            sfSettingsContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 210, Short.MAX_VALUE)
        );
        sfSettingsContainerLayout.setVerticalGroup(
            sfSettingsContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 164, Short.MAX_VALUE)
        );

        solutionValueTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Player", "Value"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Float.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane3.setViewportView(solutionValueTable);

        solutionSelector.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Shapley Value", "Aumann Dreze Value", "Owen Value", "Wiese Value", "Casajus Value", " " }));
        solutionSelector.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                solutionSelectorActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(solutionSelector, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(sfSettingsContainer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(12, 12, 12)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 308, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(calculateButton))
                .addContainerGap(42, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(solutionSelector, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(sfSettingsContainer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(calculateButton)))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(statusField, javax.swing.GroupLayout.PREFERRED_SIZE, 346, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(statusField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void statusFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_statusFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_statusFieldActionPerformed

    private void calculateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_calculateButtonActionPerformed
        progressBar.setIndeterminate(true);
        progressBar.setValue(100);
        statusField.setText("Calculating. This might take a while...");
        try {
            SolutionFunction s = sfSettingsPanel.getSF();
            if (s != null) {
                ((DefaultTableModel) solutionValueTable.getModel()).setNumRows(0);
                for (int i = 0; i < s.getCoalitionFunction().getNumPlayers(); i++) {
                    ((DefaultTableModel) solutionValueTable.getModel()).addRow(new Object[]{new Integer(i + 1), s.getValue(i)});
                }
            } else {throw new IllegalStateException();}
        } catch (IllegalStateException e) {
            statusField.setText("Solution Function could not be created");
        } catch (Exception e) {
            statusField.setText("Unknown Error. Sorry.");
        } catch (OutOfMemoryError e) {
            statusField.setText("Too many players. Reduce. Or increase JVM Heap Memory");
        }
        statusField.setText("Done");
        progressBar.setIndeterminate(false);
        progressBar.setValue(0);
    }//GEN-LAST:event_calculateButtonActionPerformed

    private void gameSelectorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_gameSelectorActionPerformed
        JComboBox cb = (JComboBox)evt.getSource();
        String cfName = (String)cb.getSelectedItem();
        updateCFSettings(cfName);
    }//GEN-LAST:event_gameSelectorActionPerformed

    private void solutionSelectorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_solutionSelectorActionPerformed
        JComboBox cb = (JComboBox)evt.getSource();
        String cfName = (String)cb.getSelectedItem();
        updateSFSettings(cfName);
    }//GEN-LAST:event_solutionSelectorActionPerformed

    private void metaGameSelectorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_metaGameSelectorActionPerformed
        JComboBox cb = (JComboBox)evt.getSource();
        String cfName = (String)cb.getSelectedItem();
        updateCFSettingsMeta(cfName);
    }//GEN-LAST:event_metaGameSelectorActionPerformed

    private void metaCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_metaCheckboxActionPerformed
        if(metaCheckbox.isSelected()){
            
        }
    }//GEN-LAST:event_metaCheckboxActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CGT_GUI().setVisible(true);
            }
        });
    }

    protected CFSettingsPanel getCFSettingsPanel(String gameType){
        if(gameType.contentEquals("Apex Game")){
            return new CFSettingsApex();
        } else if(gameType.contentEquals("Gloves Game")){
            return new CFSettingsGloves();
        } else if(gameType.contentEquals("Voting Game")){
            return new CFSettingsVoting();
        } else if(gameType.contentEquals("Voting Game")){
            return new CFSettingsVoting();
        } else if(gameType.contentEquals("Voting Game")){
            return new CFSettingsVoting();
        }
        return null;
    }

    protected SFSettingsPanel getSFSettingsPanel(String solutionType){
        if(solutionType.contentEquals("shapley")){
            return new SFSettingsShapley(cfSettingsPanel);
        } else if(solutionType.contentEquals("wiese") || solutionType.contentEquals("ad") || solutionType.contentEquals("casajus")){
            return new SFSettingsPartition(cfSettingsPanel, solutionType);
        }
        return null;
    }

    protected void updateCFSettings(String gameName){
        CFSettingsPanel newPanel = getCFSettingsPanel(gameName);
        if(cfSettingsPanel == null || newPanel.getClass() != cfSettingsPanel.getClass()){
            //cfSettingsContainer.setLayout(new java.awt.BorderLayout());
            if(metaCheckbox.isSelected()){
                if(cfSettingsPanel == null){
                    updateCFSettingsMeta((String)metaGameSelector.getSelectedItem());
                }
                ((CFSettingsMeta)cfSettingsPanel).setSubGame(newPanel);
            } else {
                cfSettingsContainer.removeAll();
                cfSettingsPanel = newPanel;
                cfSettingsContainer.add(cfSettingsPanel);
            }
            validate();
        }
    }

    protected void updateCFSettingsMeta(String gameName){
        CFSettingsPanel newPanel = null;
        //TODO remove true
        if(gameName.contentEquals("Myerson Game") || true){
            newPanel = new CFSettingsMyerson(getCFSettingsPanel((String)gameSelector.getSelectedItem()));
        }

        if(cfSettingsPanel == null || newPanel.getClass() != cfSettingsPanel.getClass()){
            //cfSettingsContainer.setLayout(new java.awt.BorderLayout());
            cfSettingsContainer.removeAll();
            cfSettingsPanel = newPanel;
            cfSettingsContainer.add(cfSettingsPanel);
            validate();
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton calculateButton;
    private javax.swing.ButtonGroup cfSelGroup;
    private javax.swing.JPanel cfSettingsContainer;
    private javax.swing.JComboBox gameSelector;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jTable1;
    private javax.swing.JCheckBox metaCheckbox;
    private javax.swing.JComboBox metaGameSelector;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.ButtonGroup sfSelGroup;
    private javax.swing.JPanel sfSettingsContainer;
    private javax.swing.JComboBox solutionSelector;
    private javax.swing.JTable solutionValueTable;
    private javax.swing.JTextField statusField;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    private CFSettingsPanel cfSettingsPanel;
    private SFSettingsPanel sfSettingsPanel;

    private void updateSFSettings(String string) {
        SFSettingsPanel sfsp = getSFSettingsPanel(string);
        if(sfSettingsPanel == null || !sfsp.getClass().equals(sfSettingsPanel.getClass())){
            sfSettingsContainer.setLayout(new java.awt.BorderLayout());
            sfSettingsContainer.removeAll();
            sfSettingsPanel = sfsp;
            sfSettingsContainer.add(sfSettingsPanel);
            validate();
        } else {
            if(sfSettingsPanel instanceof SFSettingsPartition){
                sfSettingsPanel.setSubType(string);
            }
        }
        
    }
}
